#!/bin/bash

# 获取环境变量
PLAY_HOME=/opt/playground


function installDatax()
{
 #1.在frames.txt中查看是否需要安装datax
 dataxInfo=`egrep "datax" $PLAY_HOME/frames.txt`

 datax=`echo $dataxInfo | cut -d " " -f1`
 isInstall=`echo $dataxInfo | cut -d " " -f2`
 dataxNode=`echo $dataxInfo | cut -d " " -f3`
 node=`hostname`
 
 #是否安装
 if [[ $isInstall = "true" && $dataxNode = $node ]];then
     
     #2.查看$PLAY_HOME/frames目录下是否有datax安装包
     dataxIsExists=`find $PLAY_HOME/frames -name $datax`
    
     if [[ ${#dataxIsExists} -ne 0 ]];then
           
          if [[ ! -d /opt/app ]];then
              sudo mkdir /opt/app && sudo chmod -R 775 /opt/app
          fi
   
          #删除旧的
          datax_home_old=`find /opt/app -maxdepth 1 -name "*datax*"`
          for i in $datax_home_old;do
                sudo rm -rf $i
          done

          #3.解压到指定文件夹/opt/app中
          echo "开始解压datax安装包"
          tar -zxvf $dataxIsExists -C /opt/app >& /dev/null
          echo "datax安装包解压完毕"

          datax_home=`find /opt/app -maxdepth 1 -name "*datax*"`

          #7.拷贝Mysql JDBC连接驱动
          mysqlDrive=`egrep "^mysql-drive" $PLAY_HOME/configs.txt | cut -d " " -f2`
          # 判断驱动是否存在
          driveIsExists=`find $PLAY_HOME/frames/lib -name $mysqlDrive`
          if [[ ${#driveIsExists} -ne 0 ]];then
            cp $PLAY_HOME/frames/lib/$mysqlDrive $datax_home/lib/
          else
            echo "$PLAY_HOME/frames/lib目录下没有Mysql驱动"
          fi

          #8.配置datax_HOME
          profile=/etc/profile.d/my_env.sh
          sudo sed -i "/^export datax_HOME/d" $profile
          echo "export datax_HOME=$datax_home" | sudo tee -a $profile

          #9.配置PATH
          sudo sed -i "/^export PATH=\$PATH:\$datax_HOME\/bin/d" $profile
          echo "export PATH=\$PATH:\$datax_HOME/bin" | sudo tee -a $profile

          #10.更新/etc/profile文件
          source /etc/profile && echo "更新/etc/profile环境变量完成"

          echo "--------------------------"
          echo "|  datax在$node安装成功！  |"
          echo "--------------------------"
     else
         echo "$PLAY_HOME/frames目录下没有datax安装包1"
     fi
 else
     echo "datax不允许被安装在当前节点"
 fi

}

installDatax